package com.ciccwm.auth.service;

import com.ciccwm.auth.model.AuthCodeData;
import com.ciccwm.auth.model.OAuth2TokenResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Redis降级服务.
 */
@Service
public class RedisDegradeService {
    private static final int AUTH_CODE_EXPIRATION_MINUTES = 10;
    private final RedisTemplate<String, Object> redisTemplate;

    public RedisDegradeService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void storeAuthCode(String code, AuthCodeData data) {
        redisTemplate.opsForValue().set("auth_code:" + code, data, AUTH_CODE_EXPIRATION_MINUTES, TimeUnit.MINUTES);
    }

    public AuthCodeData getAuthCode(String code) {
        return (AuthCodeData) redisTemplate.opsForValue().get("auth_code:" + code);
    }

    public void storeToken(String token, OAuth2TokenResponse response) {
        redisTemplate.opsForValue().set("token:" + token, response, response.getExpiresIn(), TimeUnit.SECONDS);
    }

    public OAuth2TokenResponse getToken(String token) {
        return (OAuth2TokenResponse) redisTemplate.opsForValue().get("token:" + token);
    }

    public void removeToken(String token) {
        redisTemplate.delete("token:" + token);
    }

    /**
     * 同步本地缓存到Redis.
     * 这个方法在定时任务中被调用，用于确保本地缓存和Redis的数据一致性.
     */
    public void syncLocalCacheToRedis() {
        // 这里可以添加同步逻辑，如果需要的话
        // 目前我们使用的是直接写入Redis的方式，所以不需要特别的同步逻辑
    }
} 
